/**
 * Created by Ysssssss on 2021/5/16.
 */
import React, { PureComponent } from 'react'
import PageBackHeader from "@common/PageBackHeader";
import {getHistoryMatchParams} from "@utils/setUrlQuery";
import {Cascader, Form, Input, Button} from "antd";
import {connect} from "react-redux";
import { getAreaJson } from "@sagas/common";
import {withRouter} from "react-router-dom";
import {telephoneValidation} from "@utils/regex";
import VerificationCode from "@common/presentational/VerificationCode";
import MapSelector from "@common/presentational/MapSelector";
import CustomizeIcon from "@common/presentational/CustomizeIcon";
import { getStoreInfo, createStore, editStore } from "@sagas/storeManagement";
import exchangeBusinessScope from "@utils/exchangeBusinessScope";

const initStoreInfo = {
    "store_name": "", // 门店名称
    "contact_name": "", // 联系人
    "contact_mobile": "",  // 联系手机号
    "business_scope": [], // 服务区域
    "district_code": "", // 所在区域，区级行政编码
    "address": "", // 详细地址
    "latitude": "", // 纬度
    "longitude": "" // 经度
}

const CODE_TYPE = 'store_contact_mobile'

@connect(({ common }) => ({
    cascaderList: common.cascaderList || []
}), {
    getAreaJson,
    getStoreInfo,
    createStore,
    editStore,
})
@withRouter
class StoreDetailPage extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            storeDetailInfo: null
        }
        this.formRef = React.createRef()
    }

    componentDidMount () {
        const { storeId } = getHistoryMatchParams(this.props)
        this.props.getAreaJson()
        if (storeId) {
            this.props.getStoreInfo({
                storeId
            }, res => {
                const {address, latitude, longitude, district_code, business_scope, ...otherInfo} = res
                this.setState({
                    storeDetailInfo: {
                        ...otherInfo,
                        addressInfo: {
                            address,
                            latitude,
                            longitude,
                            cityCode: district_code
                        },
                        business_scope: exchangeBusinessScope(business_scope)
                    }
                })
            })
        } else {
            this.setState({
                storeDetailInfo: {
                    ...initStoreInfo,
                    addressInfo: {
                        address: initStoreInfo.address,
                        latitude: initStoreInfo.latitude,
                        longitude: initStoreInfo.longitude,
                        cityCode: initStoreInfo.district_code,
                    },
                }
            })
        }

    }

    cancelEdit () {
        const { history } = this.props
        history.goBack('/store-list')
    }

    handleSubmit () {
        this.formRef.current?.submit()
    }

    handleAddressInfoChange (_, value) {
        const { latitude, longitude, address } = value
        if (!address) {
            return Promise.reject(new Error('请输入地址'))
        } else if (address.length > 50) {
            return Promise.reject(new Error('地址长度不能超过50'))
        } else if (!latitude || !longitude) {
            return Promise.reject(new Error('请在地图上选择定位门店位置'))
        } else {
            return  Promise.resolve()
        }
    }

    submitForm (values) {
        const { storeId } = getHistoryMatchParams(this.props)
        let { addressInfo, business_scope, ...params } = values
        let { cityCode, ...otherAddressInfo } = addressInfo
        params = {
            ...params,
            ...otherAddressInfo,
            district_code: `${cityCode}`,
            business_scope: business_scope[business_scope.length -1],
            code_type: CODE_TYPE
        }
        if (storeId) {
            params.storeId = storeId
            this.props.editStore(params, () => {
                this.cancelEdit()
            })
        } else {
            this.props.createStore(params, () => {
                this.cancelEdit()
            })
        }
    }

    filter(inputValue, path) {
        return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    }

    render () {
        const { cascaderList } = this.props
        const { storeDetailInfo } = this.state
        const { storeId } = getHistoryMatchParams(this.props)

        return (
            <div className="bilin-web">
                <PageBackHeader title={storeId ? '编辑店铺' : '新建店铺'} backUrl={`/store-list`}/>
                <div className="bilin-web-body form-page with-footer store-detail-page">
                    { storeDetailInfo ? (
                        <Form
                            ref={this.formRef}
                            name="store-edit"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}
                            initialValues={storeDetailInfo}
                            requiredMark={false}
                            onFinish={this.submitForm.bind(this)}
                            className="mgt-24"
                            scrollToFirstError={{
                                behavior: actions =>
                                    actions.forEach(({ el, top, left }) => {
                                        el.scrollTop = top - 100
                                        el.scrollLeft = left
                                    }),
                            }}
                        >
                            <Form.Item
                                label='店铺名称'
                                name='store_name'
                                rules={[
                                    { required: true, message: '请输入名称' },
                                ]}
                            >
                                <Input placeholder="请输入名称" disabled={storeId}/>
                            </Form.Item>
                            <Form.Item
                                label='服务区域'
                                name='business_scope'
                                rules={[
                                    {
                                        validator: (_, value) =>
                                            value.length ? Promise.resolve() : Promise.reject(new Error(`请输入/选择服务区域`)) ,
                                    }
                                ]}
                            >
                                <Cascader
                                    options={cascaderList}
                                    placeholder="请输入/选择服务区域"
                                    showSearch={{ filter: this.filter }}
                                    changeOnSelect
                                />
                            </Form.Item>
                            <Form.Item
                                label='联系人'
                                name='contact_name'
                                rules={[
                                    { required: true, message: '请输入联系人' },
                                ]}
                            >
                                <Input placeholder="请输入联系人"/>
                            </Form.Item>
                            <Form.Item
                                label='联系方式'
                                name='contact_mobile'
                                rules={[
                                    { required: true, message: '请输入手机号' },
                                    {
                                        validator: (_, value) =>
                                            telephoneValidation.test(value) ? Promise.resolve() : Promise.reject(new Error(`手机号格式不正确`)) ,
                                    }
                                ]}
                            >
                                <Input placeholder="请输入手机号" length={11}/>
                            </Form.Item>

                            <Form.Item
                                noStyle
                                shouldUpdate={(prevValues, currentValues) => prevValues.contact_mobile !== currentValues.contact_mobile}
                            >

                                { ({getFieldValue}) => {
                                    return getFieldValue('contact_mobile') !== storeDetailInfo.contact_mobile && telephoneValidation.test(getFieldValue('contact_mobile')) ? (
                                        <Form.Item
                                            label='验证码'
                                            name='code'
                                            rules={getFieldValue('contact_mobile') !== storeDetailInfo.contact_mobile ? [
                                                { required: true, message: '请输入验证码' },
                                            ] : []}
                                        >
                                            <VerificationCode codeType={CODE_TYPE} mobileNumber={this.formRef.current?.getFieldValue('contact_mobile')}/>
                                        </Form.Item>
                                    ) : null
                                } }
                            </Form.Item>

                            <Form.Item
                                label="店铺地址: "
                                name='addressInfo'
                                rules={[
                                    { required: true, message: '请输入店铺地址', },
                                    { validator: this.handleAddressInfoChange.bind(this), },
                                ]}
                            >
                                <MapSelector />
                            </Form.Item>
                            <CustomizeIcon type="tongzhi"/>
                        </Form>
                    ) : null }
                </div>
                <div className="bilin-web-footer">
                    <Button onClick={this.cancelEdit.bind(this)}>取消</Button>
                    <Button type="primary" onClick={this.handleSubmit.bind(this)}>保存</Button>
                </div>
            </div>
        )
    }
}

export default StoreDetailPage